package controller;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import data.Data;

public class RemoveBlogServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if(session.getAttribute("users")==null)
		{
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		String blog = request.getParameter("blog");
		if(blog!=null)
		{
			DBCollection collection = Data.data("blogCraw");
			DBObject object = collection.findOne(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog));
			if(object!=null)
			{
				collection.remove(object);
				
				DBCollection collection2 = Data.data("urlCraw");
				DBCursor cursor = collection2.find(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog));
				while (cursor.hasNext()) {
					DBObject dbObject2 = (DBObject) cursor.next();
					collection2.remove(dbObject2);
				}
				
				response.sendRedirect("/manager-blog?remove="+blog);
				return;
			} else {
				response.sendRedirect("/manager-blog?false=true");
				return;
			}
		} else {
			response.sendRedirect("/manager-blog");
			return;
		}
	}
}
